//
//  ViewController.m
//  Air3DViewDemo
//
//  Created by limu on 16/5/19.
//  Copyright © 2016年 SimuTech. All rights reserved.
//

#import "ViewController.h"
#import "AirSurfaceView.h"
#import "AirSegmentKey.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) AirSurfaceView        * airSurfaceView;
@property (nonatomic, strong) NSMutableArray    * contentArr;
@property (nonatomic, strong) UITableView       * tableView;
@end

@implementation ViewController
@synthesize airSurfaceView;

+(NSString *)getDocumentPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.tableView = [self setupTableView];

    // 在目录中寻找文件列表
    // 也可以通过iTunes导入共享Documents目录，使用getDocumentPath获得路径
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSError * error;
    NSArray * fileList = [fileManager contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:&error];
    self.contentArr = [[NSMutableArray alloc] init];
    [fileList enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.pathExtension isEqualToString:@"3gd"]) {
            [self.contentArr addObject:obj];
        }
    }];
    
    // 实例化控件
    self.airSurfaceView = [[AirSurfaceView alloc] initWithFrame:self.view.bounds];
    {
        // 以下为air3DView的默认设置，可以不写
        // 设置合适的裁剪 模型为unPixel像素值的时候被裁剪掉
        [airSurfaceView.airSurfaceRender setFramerate:true unPixel:10];
        // 取消边线加强，减轻负荷
        [airSurfaceView.airSurfaceRender setEffectsFastSilhouette:false];
    }
    // 显示摇杆
    [airSurfaceView showStick];
    // 显示工具栏
    [airSurfaceView showToolsBar];
    
    [self.view addSubview:airSurfaceView];
    [self.view addSubview:self.tableView];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(testPerformance) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"帧数测试" forState:UIControlStateNormal];
    btn.frame = CGRectMake(self.view.frame.size.width-90, 10, 80, 50);
    // 设置点击模型的回调
    [airSurfaceView.airSurfaceRender setSelectedBlock:^(AirSegmentKey *airSegmentKey) {
        NSLog(@"%@", airSegmentKey.guid);
    }];
    
    UIButton * backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.backgroundColor = [UIColor blueColor];
    backbtn.frame = CGRectMake(0, 0, 44, 44);
    [backbtn setTitle:@"返回" forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbtn];

}

-(void)backAction{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.tableView.frame = CGRectMake(0, 20, self.view.frame.size.width/3, 84*self.contentArr.count);
    
}

- (UITableView *)setupTableView {
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    return tableView;
}

#pragma mark - Table View UITableViewDataSource Methods
- (NSInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSInteger)section
{
    return self.contentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UITableViewCell";
    UITableViewCell * cell = [sender dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.contentView.backgroundColor = [UIColor colorWithRed:0.571 green:0.684 blue:0.743 alpha:0.483];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.numberOfLines = 3;
    }
    
    // 获取文件路径
    NSString * file = [self.contentArr objectAtIndex:indexPath.row] ;
    cell.textLabel.text = file;
    
    NSString * guid = [file stringByDeletingPathExtension];
    BOOL isModelImported = [[[airSurfaceView airSurfaceRender] loadedGuidArray] containsObject:[guid stringByDeletingPathExtension]];
    cell.detailTextLabel.text = isModelImported?@"模型 - 已载入":@"";
    return cell;
}

#pragma mark - Table View Delegate Methods

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 84;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.userInteractionEnabled = NO;
    // 获取文件路径
    NSString * guid = [self.contentArr objectAtIndex:indexPath.row];
    NSString * file = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:guid];
    BOOL isModelImported = [[[airSurfaceView airSurfaceRender] loadedGuidArray] containsObject:[guid stringByDeletingPathExtension]];
    UIActivityIndicatorView * activityIndicatorView=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    activityIndicatorView.center=self.view.center;
    [activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [activityIndicatorView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
    if (isModelImported) {
        // 已经被载入，现在使用guid卸载
        [airSurfaceView.airSurfaceRender unloadModelFile:[guid stringByDeletingPathExtension] completion:^(BOOL finished) {
            [activityIndicatorView stopAnimating];
            tableView.userInteractionEnabled = YES;
            [tableView reloadData];
            if (finished) {
                NSLog(@"unloadModelFile OK");
                [[airSurfaceView airSurfaceRender] setViewMode:ViewModeIosmetric];
            } else {
                NSLog(@"unloadModelFile error");
            }
        }];
    } else {
        // 载入文件，使用绝对路径
        [airSurfaceView.airSurfaceRender loadModelFile:file waitUntilDone:YES completion:^(BOOL finished) {
            [activityIndicatorView stopAnimating];
            tableView.userInteractionEnabled = YES;
            [tableView reloadData];
            if (finished) {
                NSLog(@"loadModelFile OK");
                [[airSurfaceView airSurfaceRender] setViewMode:ViewModeIosmetric];
            } else {
                NSLog(@"loadModelFile error");
            }
        }];
    }
}

/**
 *  性能初步测试
 */
- (void)testPerformance {
    if (airSurfaceView.airSurfaceRender.loadedGuidArray.count > 0) {
        [[airSurfaceView airSurfaceRender] testPerformance];
    }
}


//支持旋转
-(BOOL)shouldAutorotate{
    return YES;
}
//
//支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeLeft;
}

//一开始的方向  很重要
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeLeft;
}
@end
